package com.w2e.travel.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.w2e.common.utils.Result;
import com.w2e.travel.client.UserClient;
import com.w2e.travel.entity.Comment;
import com.w2e.travel.mapper.CommentMapper;
import com.w2e.travel.service.ICommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yyyl
 * @since 2024-07-07
 */
@RestController
@RequestMapping("/comments")
@RequiredArgsConstructor
public class CommentController {

    private final CommentMapper commentMapper;

    private final ICommentService commentService;

    private final UserClient userClient;

    @PostMapping
    public Result leaveOneComment(@RequestBody Comment comment){
//        System.out.println("comment = " + comment);
        comment.setCommentTime(LocalDateTime.now());
        commentMapper.insert(comment);
        return new Result(200,comment,"评论成功！");
    }

    @GetMapping
    public Map<String,Object> getTop10CommentsOrderedByTimeDesc(@RequestParam("travelogueId") Integer tId) {
        LambdaQueryWrapper<Comment> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Comment::getTravelogueId,tId);
        lqw.orderByDesc(Comment::getCommentTime);

        // 创建分页对象，限制查询结果为 5 条
        Page<Comment> page = new Page<>(1, 5);
        Page<Comment> commentPage = commentMapper.selectPage(page, lqw);

        List<Comment> comments = commentPage.getRecords();
        List<Result> results = new ArrayList<>();
        comments.forEach( item ->{
            Result result  = userClient.getById(item.getCommenterId());
            results.add(result);
        });

        Map map = new HashMap();
        map.put("comments",comments);
        map.put("users",results);

        return map;
    }
}
